from django.shortcuts import render, HttpResponse
from user.models import User


# Create your views here.
def index_handler(request):
    # 查找到所有的user对象
    users = User.objects.all()

    # 渲染模板，把users传递过去
    return render(request, 'index.html', context={'users': users})


def add_handler(request):
    if "GET" == request.method:
        # GET方法，直接返回页面
        return render(request, 'add.html')
    else:
        # 获取表单中数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        age = request.POST.get('age')
        email = request.POST.get('email')

        try:
            # 写入数据库
            User.objects.create(username=username, password=password, age=age, email=email)

            # 写入成功
            return render(request, 'result.html', context={'message': '添加用户成功'})
        except:
            # 写入失败
            return render(request, 'result.html', context={'message': '添加用户失败'})
        finally:
            pass


def alter_handler(request, id):
    usr = User.objects.get(id=id)

    if request.method == "GET":
        return render(request, "alter.html", {"user": usr})
    else:
        usr.username = request.POST.get('username')
        usr.password = request.POST.get('password')
        usr.age = request.POST.get('age')
        usr.email = request.POST.get('email')
        try:
            # 执行修改
            usr.save()

            # 修改成功
            return render(request, "result.html", {"message": "修改用户成功"})
        except:
            # 修改失败
            return render(request, "result.html", {"message": "修改用户失败"})


def del_handler(request, id):
    try:
        # 执行删除操作
        User.objects.get(id=id).delete()

        # 删除成功
        return render(request, 'result.html', {"message": '删除用户成功'})
    except:
        # 删除失败
        return render(request, 'result.html', {"message": '删除用户失败'})
